#pragma once


#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <memory>
#include <time.h>
#include "Mutex.hpp"


namespace LogModule
{
    using namespace LockModule;
    //构成: 1. 构建日志字符串 2.刷新落盘(screen,file)
    //1.日志默认路径和文件名
    const std::string defaultlogpath = "./log/";
    const std::string defaultlogname = "log.txt";

    //2.日志等级
    enum LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string LevelToString(LogLevel level)
    {
        switch(level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }

    //3.刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;//防止内存泄漏
        virtual void SyncLog(const std::string& message) = 0;
    };
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy()
        {
        }
        ~ConsoleLogStrategy()
        {
        }
        void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_lock);
            std::cout << message << std::endl;
        }
    private:
        Mutex _lock;
    };

    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string& logpath = defaultlogpath,
            const std::string& logname = defaultlogname)
            :_logname(logname),
             _logpath(logpath)
        {
            LockGuard lockguard(_lock);
            //确认路径和文件名存在
            if(std::filesystem::exists(_logpath))
            {
                return;
            }

            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch(const std::filesystem::filesystem_error& e)
            {
                std::cerr << e.what() << '\n'; 
            }
        }
        ~FileLogStrategy()
        {
        }
        void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_lock);
            std::string log = _logpath + _logname; // ./log/log.txt
            std::ofstream out(log,std::ios::app); //不存在就新建,存在就追加
            if(!out.is_open())
            {
                return;
            }
            // out.write(message.c_str(),sizeof(message));
            out << message << "\n";
            out.close();
        }
    private:
        std::string _logpath;
        std::string _logname;
        Mutex _lock;
    };

    //获取一些当前系统时间
    std::string CurrentTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp,&curr);
        char buffer[1024];
        snprintf(buffer,sizeof(buffer),"%4d-%02d-%02d %02d:%02d:%02d",
            curr.tm_year + 1900,
            curr.tm_mon + 1,
            curr.tm_mday,
            curr.tm_hour,
            curr.tm_min,
            curr.tm_sec
        );
        return buffer;
    }
    // std::string GetCurrTime()
    // {
    //     time_t t = time(nullptr);
    //     struct tm* curr = ::localtime(&t);
    //     char currtime[32];
    //     snprintf(currtime,sizeof(currtime),"%d-%d-%d %d:%d:%d",
    //         curr->tm_year + 1900,
    //         curr->tm_mon + 1,
    //         curr->tm_mday,
    //         curr->tm_hour,
    //         curr->tm_min,
    //         curr->tm_sec
    //     );
    //     return currtime;
    // }

    //4.构建日志字符串,根据策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            //默认采用屏幕刷新策略
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableConsleLog()
        {
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Logger()
        {

        }
        //一条完整的信息: [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16] + 日志自定义部分
        class LogMessage
        {
        public:
            LogMessage(LogLevel level,const std::string& filename,int line,Logger& logger):
                _currtime(CurrentTime()),
                _level(level),
                _pid(::getpid()),
                _filename(filename),
                _line(line),
                _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "] " << "[" << LevelToString(_level) << "] "
                         << "[" << _pid << "] " << "[" << _filename <<"] "
                         << "[" << _line << "] " << " - ";
                _loginfo = ssbuffer.str();
            }
            template<class T>
            LogMessage& operator<<(const T& info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }
            ~LogMessage()
            {
                if(_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }
        private:
            std::string _currtime; //日志时间
            LogLevel _level;       //日志等级
            pid_t _pid;            //进程pid
            std::string _filename; //文件名称
            int _line;             //日志所在行号
            Logger& _logger;       //根据不同的策略进行刷新
            std::string _loginfo;  //一条完整的日志记录
        };
        LogMessage operator()(LogLevel level,const std::string& filename,int line)
        {
            return LogMessage(level,filename,line,*this);
        }
    private:
        std::shared_ptr<LogStrategy> _strategy;
    };
    Logger logger;
#define LOG(Level) logger(Level,__FILE__,__LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsleLog()
#define ENABLE_FILE_LOG() logger.EnableFileLog()

//LOG(DEBUG) << xx << aa << bb;
//LOgMessage << xx << aa << bb;
}
